package cn.com.pansky.service;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.vsame.url2sql.action.BaseAction;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.sql.Model;
import net.vsame.url2sql.utils.PostParam;
import cn.com.pansky.helper.PostHelper;
import cn.com.pansky.helper.PostHelper_zgss;
import cn.com.pansky.sdk.API;
import cn.com.pansky.util.CardNumUtil;
import cn.com.pansky.util.CommonUtils;
import cn.com.pansky.util.HttpUtil;
import cn.com.pansky.util.LssConstant;
import cn.com.pansky.util.SendMsgUtil;

import com.alibaba.fastjson.JSONObject;

public class CommonService extends BaseAction {

	Connection conn = null;
	PreparedStatement pstat = null;

	/**
	 * 图片识别
	 * 
	 * @param path
	 *            图片路径
	 * @return
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */
	public JSONObject idendetify(String path) throws KeyManagementException,
			NoSuchAlgorithmException, IOException {
		JSONObject json = new JSONObject();
		File file = new File(path);// 身份证上传后的临时文件
		
//		Map<String, String> filess = new HashMap<String,String>();
//		String u_featrue2 = null ;
		if (file.exists()) {
//			HttpUtil.enableAllHost();
//			filess.put("image", path);
//			Map<String, String> paramss = new HashMap<String, String>();
			//获取人脸特征
//			String results = HttpUtil.post(LssConstant.FACE_URL_EXTRACT, paramss, filess);
//			JSONObject jsonObjects = (JSONObject) JSONObject.parse(results);
//			System.out.println(jsonObjects);
//			JSONArray faces = jsonObjects.getJSONArray("faces");
//			if (!(faces.size()>0)) {
//				json.put("isOK", false);
//			} else {
				// 调用接口识别身份证图片，解析出姓名，身份证，民族，性别，出生年月
				Map<String, String> files = new HashMap<String, String>();
				Map<String, String> params = new HashMap<String, String>();
				files.put("image", file.getPath());
				String result = "";
				// 1.调用远程接口
				HttpUtil.enableAllHost();
				result = HttpUtil.post(LssConstant.FACE_URL_IDCARD, params, files);
				System.out.println("识别结果+"+result);
				JSONObject jsonObject = new JSONObject();
				if (null != result || !"".equals(result)) {
					jsonObject = (JSONObject) JSONObject.parse(result);
				}
				if (!"".equals(jsonObject) && null != jsonObject
						&& jsonObject.getString("id_card_number") != null
						&& !jsonObject.getString("id_card_number").equals("")) {
					String aac002 = jsonObject.getString("id_card_number");// 身份证号
					aac002 = CardNumUtil.cardNum(aac002);
					if (!CommonUtils.isIdentityId(aac002)) {// 对识别结果进行校验
						json.put("isOK", false);
					} else {
						String birthday = jsonObject.getString("birthday");// 出生年月
						// 将日期json转换为日期格式
						if (birthday != null && !birthday.equals("")) {
							JSONObject jsonBirth = (JSONObject) JSONObject
									.parse(birthday);
							birthday = jsonBirth.getString("year") + "-"
									+ jsonBirth.getString("month") + "-"
									+ jsonBirth.getString("day");
						}
	
						json.put("CA003", jsonObject.getString("name"));
						json.put("CA006", aac002);
						json.put("CA051", jsonObject.getString("race"));
						json.put("CA050", jsonObject.getString("gender"));
						json.put("CA009", birthday == null ? "" : birthday);
						json.put("CA052", jsonObject.getString("address"));
						json.put("isOK", true);
					}
				}
//			}
		} else {
			json.put("isOK", false);
		}
		return json;
	}

	/**
	 * 发送短信验证码
	 * 
	 * @param AA032
	 * @param msg
	 * @return
	 * @throws Exception
	 */
//	public String sendCode(String AA032) throws Exception {
//		SendMsgUtil sendmsg = new SendMsgUtil();
//		String code = SendMsgUtil.generateCode();
//		System.out.println(aliyunSms(AA032));
//		SqlHelper.execute("insert into CA20 values(${~UUID}, ?, ?, ?, ?)",
//				AA032, new java.sql.Timestamp(System.currentTimeMillis()),
//				code, new Timestamp(System.currentTimeMillis()).getTime());
//		
// 		return code;
//	}

	/**
	 * 阿里云发送短信接口
	 * @param AA032 手机号
	 * @return
	 * @throws Exception
	 */
	public JSONObject aliyunSms(String AA032) throws Exception {
		String code = SendMsgUtil.generateCode();
		SqlHelper.execute("insert into CA20 values(${~UUID}, ?, ?, ?, ?)",
				AA032, new java.sql.Timestamp(System.currentTimeMillis()),
				code, new Timestamp(System.currentTimeMillis()).getTime());
		
		List<PostParam> params = new ArrayList<PostParam>();
 		PostParam e2 = new PostParam("content", "string", code);
 		PostParam e3 = new PostParam("phone", "string", AA032);
 		params.add(e2);
 		params.add(e3);
 		JSONObject obj = PostHelper.send("public/sms.json", params);
 		obj.put("content", code);
		return obj;
	}
	
	
	/**
	 * 阿里云发送短信（职工）
	 * @param phone  手机号
	 * @param msg  短信内容
	 * @return
	 * @throws Exception
	 */
	public JSONObject aliyunSms_zgss(String phone,String msg) throws Exception {
		List<PostParam> params = new ArrayList<PostParam>();
 		PostParam e2 = new PostParam("content", "string", msg);
 		PostParam e3 = new PostParam("phone", "string", phone);
 		params.add(e2);
 		params.add(e3);
 		JSONObject obj = PostHelper_zgss.send("public/sms.json", params);
		return obj;
	}
	
	
	public void isInsured() {

		// 入参：AAA121:QNWAC01
		// AAC002:身份证数组
		// queryRegisterVerify

		JSONObject param = new JSONObject();
		param.put("AAA121", "QNWAC01"); // 缴费标识
		param.put("AAC002", new String[] { "612429198908280783" }); // 当事人缴费账号
		System.out.println(param.toString());
		JSONObject object = API.sendController("queryRegisterVerify.json",
				param);
		System.out.println("业务系统数据返回结果：" + object);
	}

	/**
	 * 记录证件信息
	 * 
	 * @param infile
	 * @param aac001
	 * @throws Exception
	 */
	public String isnertRC05(String ca001, String infile, String id) throws Exception {
		FileInputStream fis = null;
		Connection conn = WebHelper.getContext().getConn();
		if(!"".equals(id)) {
			pstat = conn.prepareStatement("DELETE FROM RC05 WHERE CA020 = '"+ id+"'");
			pstat.executeUpdate();
		}else{
			id = UUID.randomUUID().toString();
		}
		try {

			File file = new File(infile);
			fis = new FileInputStream(file);
			pstat = conn
					.prepareStatement("INSERT INTO RC05(CA020, CA001, CA005, CA022, CA060) VALUES(?, ?, '2', ?, ?)");
			pstat.setString(1, id); // id
			pstat.setString(2, ca001); // id
			pstat.setBinaryStream(3, fis, fis.available()); // 时间
			pstat.setString(4,
					new SimpleDateFormat("yyyy-MM-dd").format(new Date())); // 二进制文件
			pstat.executeUpdate();
			conn.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("[blobInsert error : ]" + ex.toString());
		}

		return id;
	}

	/**
	 * 记录人员特征信息
	 * @param infile 图片
	 * @param ca001 人员ID 
	 * @param ca016 相似度
	 * @return
	 * @throws Exception
	 */
	public String isnertRC06(String infile, String ca001, Double ca016, String id)
			throws Exception {
		FileInputStream fis = null;
		Connection conn = WebHelper.getContext().getConn();
		if(!"".equals(id)) {
			pstat = conn.prepareStatement("DELETE FROM RC06 WHERE CA011 = '"+ id+"'");
			pstat.executeUpdate();
		}else{
			id = UUID.randomUUID().toString();
		}
		try {
			File file = new File(infile);
			fis = new FileInputStream(file);
			pstat = conn
					.prepareStatement("INSERT INTO RC06 (CA011, CA001, CA012, CA015, CA014, CA016) VALUES (?, ?, ?, ?, ?, ?) ");
			pstat.setString(1, id); // id
			pstat.setString(2, ca001); // 人员ID
			pstat.setString(3, "001"); // 面部特征
			pstat.setBinaryStream(4, fis, fis.available()); // 照片
			pstat.setString(5,
					new SimpleDateFormat("yyyy-MM-dd").format(new Date())); // 时间
			pstat.setDouble(6, ca016); // 相似度
			pstat.executeUpdate();
			conn.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("[blobInsert error : ]" + ex.toString());
		}

		return id;
	}



	/**
	 * 转换图片为二进制
	 * 
	 * @param in
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public byte[] changeImage2Bytes(BufferedInputStream in)
			throws FileNotFoundException, IOException {
		byte[] temp = new byte[1024];
		int size = 0;
		byte[] content = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
			while ((size = in.read(temp)) != -1) {
				out.write(temp, 0, size);
			}
			in.close();
			content = out.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return content;
	}

	public void getIdcardPic(String CA001, String filename) {
		conn = WebHelper.getContext().getConn();
		ResultSet rs = null;
		FileOutputStream fos = null;
		String sql = "SELECT CA022 FROM RC05 WHERE CA001 = ?";
		try {
			pstat = conn.prepareStatement(sql);
			pstat.setString(1, CA001);
			rs = pstat.executeQuery();
			if (rs.next()) {
				InputStream in = null;
				Blob blob = (Blob) rs.getBlob("CA022");
				if (null != blob) {
					in = blob.getBinaryStream();
					BufferedInputStream bfin = new BufferedInputStream(in);
					byte[] bytes = this.changeImage2Bytes(bfin);
					if (null != bytes) {
						fos = new FileOutputStream(filename);
						fos.write(bytes);
						fos.close();
					}
				}
			} 
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 根据静态代码值获取 name
	 * @param codeName
	 * @param value
	 * @return
	 */
	public String getNameByValue(String codeName, String value) {
		String sql2 = "select AAA102 from AA11 where AAA100 = '"+codeName+"' and AAA102 = "+value+" and AAA111 = '1'";
		Model m3 = SqlHelper.queryOne(sql2);
		if(m3 != null) {
			return m3.getString("AAA103");
		}
		return "";
	}
	
	/**
	 * 根据name 获取码值
	 * @param codeName
	 * @param value
	 * @return
	 */
	public String getValueByName(String codeName, String name) {
		String sql2 = "select AAA102 from AA11 where AAA100 = '"+codeName+"' and AAA103 like '%"+name+"%' and AAA111 = '1'";
		Model m3 = SqlHelper.queryOne(sql2);
		if(m3 != null) {
			return m3.getString("AAA102");
		}
		return "";
	}
	
	/**
	 * 转换性别
	 * @param CA050
	 * @return
	 */
	public String getAac004(String CA050) {
		return CA050.equals("男") ? "1" : "2";
	}
	
	public static void main(String[] args) {

	}

}
